package com.cxb.utils;

import java.util.HashMap;
import java.util.Locale;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.Toast;

public class Tts implements OnInitListener {
	private static TextToSpeech tts = null;
	private static TtsStateListener ttsStateListener = null;
	private static boolean isInit=false;
	public Tts(Context context) {
		isInit=false;
		Log.i("test", "ami tts initing "); 

		tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
			public void onInit(int status) { 
				
				Log.i("test", "ami tts state= "+status);
				if (status != 0) {
					return;
				}

				isInit=true;
				int result = Tts.this.tts.setLanguage(Locale.CHINA);
				if ((result == -1) || (result == -2)) {
				} else {
					Tts.this.tts
							.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
								public void onUtteranceCompleted(
										String utteranceId) {
									Tts.this.ttsStateListener
											.ttsStateChange(Tts.TtsState.STOP);
								}
							});
				}
			}
		});
		

	}

	public static boolean speak(String text) {
		try {


			tts.speak(text, TextToSpeech.QUEUE_ADD, null);
			ttsStateListener.ttsStateChange(TtsState.START);
			return true;
		} catch (Exception e) {
			try {

				ttsStateListener.ttsStateChange(TtsState.STOP);
			} catch (Exception e2) {
			}
		}
		return false;
	}
	public static void showToast(Context context,String text,int duration){
		Toast.makeText(context, text, duration).show();
		speak(text);
	}

	public static void stop() {
		if ((tts != null) && (tts.isSpeaking())) {
			ttsStateListener.ttsStateChange(TtsState.STOP);
			tts.stop();
		}
	}

	public static boolean isSpeaking() {
		if (tts != null)
			return tts.isSpeaking();
		return false;
	}

	public void release() {
		if (this.tts != null) {
			stop();
			this.tts.shutdown();
			this.tts = null;
		}
	}

	protected void finalize() throws Throwable {
		release();
		super.finalize();
	}

	public void registerTtsStateChange(TtsStateListener ttsStateListener) {
		this.ttsStateListener = ttsStateListener;
	}

	public static enum TtsState {
		IDLE, START, STOP;
	}

	public static abstract interface TtsStateListener {
		public abstract int ttsStateChange(Tts.TtsState paramTtsState);
	}

	@Override
	public void onInit(int status) {
		tts.setLanguage(Locale.CHINA);
		
	}
}
